/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javolution.util.FastList;
import javolution.util.FastMap;
import jmmos.Config;
import jmmos.MMODatabaseFactory;
import jmmos.gameserver.cache.CrestCache;
import jmmos.gameserver.datatables.GuildTable;
import jmmos.gameserver.datatables.SkillTable;
import jmmos.gameserver.instancemanager.CastleManager;
import jmmos.gameserver.instancemanager.FortManager;
import jmmos.gameserver.instancemanager.SiegeManager;
import jmmos.gameserver.instancemanager.TerritoryWarManager;
import jmmos.gameserver.instancemanager.TerritoryWarManager.Territory;
import jmmos.gameserver.model.actor.instance.MMOPcInstance;
import jmmos.gameserver.model.itemcontainer.GuildWarehouse;
import jmmos.gameserver.model.itemcontainer.ItemContainer;
import jmmos.gameserver.model.skills.MMOSkill;
import jmmos.gameserver.model.zone.ZoneId;
import jmmos.gameserver.network.SystemMessageId;
import jmmos.gameserver.network.serverpackets.CreatureSay;
import jmmos.gameserver.network.serverpackets.ExBrExtraUserInfo;
import jmmos.gameserver.network.serverpackets.ExSubPledgeSkillAdd;
import jmmos.gameserver.network.serverpackets.ItemList;
import jmmos.gameserver.network.serverpackets.MMOGameServerPacket;
import jmmos.gameserver.network.serverpackets.PledgeReceiveSubPledgeCreated;
import jmmos.gameserver.network.serverpackets.PledgeShowInfoUpdate;
import jmmos.gameserver.network.serverpackets.PledgeShowMemberListAll;
import jmmos.gameserver.network.serverpackets.PledgeShowMemberListDeleteAll;
import jmmos.gameserver.network.serverpackets.PledgeShowMemberListUpdate;
import jmmos.gameserver.network.serverpackets.PledgeSkillList;
import jmmos.gameserver.network.serverpackets.PledgeSkillList.SubPledgeSkill;
import jmmos.gameserver.network.serverpackets.PledgeSkillListAdd;
import jmmos.gameserver.network.serverpackets.SkillCoolTime;
import jmmos.gameserver.network.serverpackets.StatusUpdate;
import jmmos.gameserver.network.serverpackets.SystemMessage;
import jmmos.gameserver.network.serverpackets.UserInfo;
import jmmos.gameserver.scripting.scriptengine.events.GuildCreationEvent;
import jmmos.gameserver.scripting.scriptengine.events.GuildJoinEvent;
import jmmos.gameserver.scripting.scriptengine.events.GuildLeaderChangeEvent;
import jmmos.gameserver.scripting.scriptengine.events.GuildLeaveEvent;
import jmmos.gameserver.scripting.scriptengine.events.GuildLevelUpEvent;
import jmmos.gameserver.scripting.scriptengine.listeners.guild.GuildCreationListener;
import jmmos.gameserver.scripting.scriptengine.listeners.guild.GuildMembershipListener;
import jmmos.gameserver.util.Util;

public class MMOGuild
{
	private static final Logger _log = Logger.getLogger(MMOGuild.class.getName());
	
	// SQL queries
	private static final String INSERT_GUILD_DATA = "INSERT INTO guild_data (guild_id,guild_name,guild_level,hasCastle,blood_alliance_count,blood_oath_count,ally_id,ally_name,leader_id,crest_id,crest_large_id,ally_crest_id) values (?,?,?,?,?,?,?,?,?,?,?,?)";
	private static final String SELECT_GUILD_DATA = "SELECT guild_name,guild_level,hasCastle,blood_alliance_count,blood_oath_count,ally_id,ally_name,leader_id,crest_id,crest_large_id,ally_crest_id,reputation_score,auction_bid_at,ally_penalty_expiry_time,ally_penalty_type,char_penalty_expiry_time,dissolving_expiry_time FROM guild_data where guild_id=?";
	
	private static List<GuildCreationListener> guildCreationListeners = new FastList<GuildCreationListener>().shared();
	private static List<GuildMembershipListener> guildMembershipListeners = new FastList<GuildMembershipListener>().shared();
	
	private String _name;
	private int _guildId;
	private MMOGuildMember _leader;
	private final Map<Integer, MMOGuildMember> _members = new FastMap<>();
	
	private String _allyName;
	private int _allyId;
	private int _level;
	private int _castleId;
	private int _fortId;
	private int _hideoutId;
	private int _hiredGuards;
	private int _crestId;
	private int _crestLargeId;
	private int _allyCrestId;
	private int _auctionBiddedAt = 0;
	private long _allyPenaltyExpiryTime;
	private int _allyPenaltyType;
	private long _charPenaltyExpiryTime;
	private long _dissolvingExpiryTime;
	private int _bloodAllianceCount;
	private int _bloodOathCount;
	
	// Ally Penalty Types
	/** Guild leaved ally */
	public static final int PENALTY_TYPE_GUILD_LEAVED = 1;
	/** Guild was dismissed from ally */
	public static final int PENALTY_TYPE_GUILD_DISMISSED = 2;
	/** Leader guild dismiss guild from ally */
	public static final int PENALTY_TYPE_DISMISS_GUILD = 3;
	/** Leader guild dissolve ally */
	public static final int PENALTY_TYPE_DISSOLVE_ALLY = 4;
	
	private final ItemContainer _warehouse = new GuildWarehouse(this);
	private final List<Integer> _atWarWith = new FastList<>();
	private final List<Integer> _atWarAttackers = new FastList<>();
	
	// Guild Privileges
	/** No privilege to manage any guild activity */
	public static final int CP_NOTHING = 0;
	/** Privilege to join guild */
	public static final int CP_CL_JOIN_GUILD = 2;
	/** Privilege to give a title */
	public static final int CP_CL_GIVE_TITLE = 4;
	/** Privilege to view warehouse content */
	public static final int CP_CL_VIEW_WAREHOUSE = 8;
	/** Privilege to manage guild ranks */
	public static final int CP_CL_MANAGE_RANKS = 16;
	public static final int CP_CL_PLEDGE_WAR = 32;
	public static final int CP_CL_DISMISS = 64;
	/** Privilege to register guild crest */
	public static final int CP_CL_REGISTER_CREST = 128;
	public static final int CP_CL_APPRENTICE = 256;
	public static final int CP_CL_TROOPS_FAME = 512;
	public static final int CP_CL_SUMMON_AIRSHIP = 1024;
	/** Privilege to open a door */
	public static final int CP_CH_OPEN_DOOR = 2048;
	public static final int CP_CH_OTHER_RIGHTS = 4096;
	public static final int CP_CH_AUCTION = 8192;
	public static final int CP_CH_DISMISS = 16384;
	public static final int CP_CH_SET_FUNCTIONS = 32768;
	public static final int CP_CS_OPEN_DOOR = 65536;
	public static final int CP_CS_MANOR_ADMIN = 131072;
	public static final int CP_CS_MANAGE_SIEGE = 262144;
	public static final int CP_CS_USE_FUNCTIONS = 524288;
	public static final int CP_CS_DISMISS = 1048576;
	public static final int CP_CS_TAXES = 2097152;
	public static final int CP_CS_MERCENARIES = 4194304;
	public static final int CP_CS_SET_FUNCTIONS = 8388608;
	/** Privilege to manage all guild activity */
	public static final int CP_ALL = 16777214;
	
	// Sub-unit types
	/** Guild subunit type of Academy */
	public static final int SUBUNIT_ACADEMY = -1;
	/** Guild subunit type of Royal Guard A */
	public static final int SUBUNIT_ROYAL1 = 100;
	/** Guild subunit type of Royal Guard B */
	public static final int SUBUNIT_ROYAMMO = 200;
	/** Guild subunit type of Order of Knights A-1 */
	public static final int SUBUNIT_KNIGHT1 = 1001;
	/** Guild subunit type of Order of Knights A-2 */
	public static final int SUBUNIT_KNIGHT2 = 1002;
	/** Guild subunit type of Order of Knights B-1 */
	public static final int SUBUNIT_KNIGHT3 = 2001;
	/** Guild subunit type of Order of Knights B-2 */
	public static final int SUBUNIT_KNIGHT4 = 2002;
	
	/** FastMap(Integer, MMOSkill) containing all skills of the MMOGuild */
	private final Map<Integer, MMOSkill> _skills = new FastMap<>();
	private final Map<Integer, RankPrivs> _privs = new FastMap<>();
	private final Map<Integer, SubPledge> _subPledges = new FastMap<>();
	private final Map<Integer, MMOSkill> _subPledgeSkills = new FastMap<>();
	
	private int _reputationScore = 0;
	private int _rank = 0;
	
	private String _notice;
	private boolean _noticeEnabled = false;
	private static final int MAX_NOTICE_LENGTH = 8192;
	
	/**
	 * Called if a guild is referenced only by id. In this case all other data needs to be fetched from db
	 * @param guildId A valid guild Id to create and restore
	 */
	public MMOGuild(int guildId)
	{
		_guildId = guildId;
		initializePrivs();
		restore();
		getWarehouse().restore();
	}
	
	/**
	 * Called only if a new guild is created
	 * @param guildId A valid guild Id to create
	 * @param guildName A valid guild name
	 */
	public MMOGuild(int guildId, String guildName)
	{
		_guildId = guildId;
		_name = guildName;
		initializePrivs();
		fireGuildCreationListeners();
	}
	
	/**
	 * @return Returns the guildId.
	 */
	public int getGuildId()
	{
		return _guildId;
	}
	
	/**
	 * @param guildId The guildId to set.
	 */
	public void setGuildId(int guildId)
	{
		_guildId = guildId;
	}
	
	/**
	 * @return Returns the leaderId.
	 */
	public int getLeaderId()
	{
		return (_leader != null ? _leader.getObjectId() : 0);
	}
	
	/**
	 * @return MMOGuildMember of guild leader.
	 */
	public MMOGuildMember getLeader()
	{
		return _leader;
	}
	
	/**
	 * @param leader the leader to set.
	 */
	public void setLeader(MMOGuildMember leader)
	{
		_leader = leader;
		_members.put(leader.getObjectId(), leader);
	}
	
	public void setNewLeader(MMOGuildMember member)
	{
		if (!getLeader().isOnline())
		{
			return;
		}
		if (member == null)
		{
			return;
		}
		if (!member.isOnline())
		{
			return;
		}
		
		MMOPcInstance exLeader = getLeader().getPlayerInstance();
		MMOPcInstance newLeader = member.getPlayerInstance();
		if (!fireGuildLeaderChangeListeners(newLeader, exLeader))
		{
			return;
		}
		
		SiegeManager.getInstance().removeSiegeSkills(exLeader);
		exLeader.setGuild(this);
		exLeader.setGuildPrivileges(MMOGuild.CP_NOTHING);
		exLeader.broadcastUserInfo();
		
		setLeader(member);
		updateGuildInDB();
		
		exLeader.setPledgeClass(MMOGuildMember.calculatePledgeClass(exLeader));
		exLeader.broadcastUserInfo();
		exLeader.checkItemRestriction();
		newLeader.setGuild(this);
		newLeader.setPledgeClass(MMOGuildMember.calculatePledgeClass(newLeader));
		newLeader.setGuildPrivileges(MMOGuild.CP_ALL);
		if (getLevel() >= SiegeManager.getInstance().getSiegeGuildMinLevel())
		{
			SiegeManager.getInstance().addSiegeSkills(newLeader);
			
			// Transferring siege skills TimeStamps from old leader to new leader to prevent unlimited headquarters
			if (!exLeader.getSkillReuseTimeStamps().isEmpty())
			{
				TimeStamp t;
				for (MMOSkill sk : SkillTable.getInstance().getSiegeSkills(newLeader.isNoble(), getCastleId() > 0))
				{
					if (exLeader.hasSkillReuse(sk.getReuseHashCode()))
					{
						t = exLeader.getSkillReuseTimeStamp(sk.getReuseHashCode());
						newLeader.addTimeStamp(sk, t.getReuse(), t.getStamp());
					}
				}
				newLeader.sendPacket(new SkillCoolTime(newLeader));
			}
		}
		newLeader.broadcastUserInfo();
		
		broadcastGuildStatus();
		
		SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.GUILD_LEADER_PRIVILEGES_HAVE_BEEN_TRANSFERRED_TO_C1);
		sm.addString(newLeader.getName());
		broadcastToOnlineMembers(sm);
		sm = null;
	}
	
	/**
	 * @return the guild leader's name.
	 */
	public String getLeaderName()
	{
		if (_leader == null)
		{
			_log.warning(MMOGuild.class.getName() + ": Guild " + getName() + " without guild leader!");
			return "";
		}
		return _leader.getName();
	}
	
	/**
	 * @return the guild name.
	 */
	public String getName()
	{
		return _name;
	}
	
	/**
	 * @param name The name to set.
	 */
	public void setName(String name)
	{
		_name = name;
	}
	
	/**
	 * Adds a guild member to the guild.
	 * @param member the guild member.
	 */
	private void addGuildMember(MMOGuildMember member)
	{
		_members.put(member.getObjectId(), member);
	}
	
	/**
	 * Adds a guild member to the guild.<br>
	 * Using a different constructor, to make it easier to read.
	 * @param player the guild member
	 */
	public void addGuildMember(MMOPcInstance player)
	{
		if (!fireGuildJoinListeners(player))
		{
			return;
		}
		
		final MMOGuildMember member = new MMOGuildMember(this, player);
		// store in memory
		addGuildMember(member);
		member.setPlayerInstance(player);
		player.setGuild(this);
		player.setPledgeClass(MMOGuildMember.calculatePledgeClass(player));
		player.sendPacket(new PledgeShowMemberListUpdate(player));
		player.sendPacket(new PledgeSkillList(this));
		addSkillEffects(player);
	}
	
	/**
	 * Updates player status in guild.
	 * @param player the player to be updated.
	 */
	public void updateGuildMember(MMOPcInstance player)
	{
		final MMOGuildMember member = new MMOGuildMember(player.getGuild(), player);
		if (player.isGuildLeader())
		{
			setLeader(member);
		}
		
		addGuildMember(member);
	}
	
	/**
	 * @param name the name of the required guild member.
	 * @return the guild member for a given name.
	 */
	public MMOGuildMember getGuildMember(String name)
	{
		for (MMOGuildMember temp : _members.values())
		{
			if (temp.getName().equals(name))
			{
				return temp;
			}
		}
		return null;
	}
	
	/**
	 * @param objectID the required guild member object Id.
	 * @return the guild member for a given {@code objectID}.
	 */
	public MMOGuildMember getGuildMember(int objectID)
	{
		return _members.get(objectID);
	}
	
	/**
	 * @param objectId the object Id of the member that will be removed.
	 * @param guildJoinExpiryTime time penalty to join a guild.
	 */
	public void removeGuildMember(int objectId, long guildJoinExpiryTime)
	{
		if (!fireGuildLeaveListeners(objectId))
		{
			return;
		}
		
		final MMOGuildMember exMember = _members.remove(objectId);
		if (exMember == null)
		{
			_log.warning("Member Object ID: " + objectId + " not found in guild while trying to remove");
			return;
		}
		final int leadssubpledge = getLeaderSubPledge(objectId);
		if (leadssubpledge != 0)
		{
			// Sub-unit leader withdraws, position becomes vacant and leader
			// should appoint new via NPC
			getSubPledge(leadssubpledge).setLeaderId(0);
			updateSubPledgeInDB(leadssubpledge);
		}
		
		if (exMember.getApprentice() != 0)
		{
			final MMOGuildMember apprentice = getGuildMember(exMember.getApprentice());
			if (apprentice != null)
			{
				if (apprentice.getPlayerInstance() != null)
				{
					apprentice.getPlayerInstance().setSponsor(0);
				}
				else
				{
					apprentice.setApprenticeAndSponsor(0, 0);
				}
				
				apprentice.saveApprenticeAndSponsor(0, 0);
			}
		}
		if (exMember.getSponsor() != 0)
		{
			final MMOGuildMember sponsor = getGuildMember(exMember.getSponsor());
			if (sponsor != null)
			{
				if (sponsor.getPlayerInstance() != null)
				{
					sponsor.getPlayerInstance().setApprentice(0);
				}
				else
				{
					sponsor.setApprenticeAndSponsor(0, 0);
				}
				
				sponsor.saveApprenticeAndSponsor(0, 0);
			}
		}
		exMember.saveApprenticeAndSponsor(0, 0);
		if (Config.REMOVE_CASTLE_CIRCLETS)
		{
			CastleManager.getInstance().removeCirclet(exMember, getCastleId());
		}
		if (exMember.isOnline())
		{
			MMOPcInstance player = exMember.getPlayerInstance();
			if (!player.isNoble())
			{
				player.setTitle("");
			}
			player.setApprentice(0);
			player.setSponsor(0);
			
			if (player.isGuildLeader())
			{
				SiegeManager.getInstance().removeSiegeSkills(player);
				player.setGuildCreateExpiryTime(System.currentTimeMillis() + (Config.ALT_GUILD_CREATE_DAYS * 86400000L)); // 24*60*60*1000 = 86400000
			}
			// remove Guild skills from Player
			removeSkillEffects(player);
			
			// remove Residential skills
			if (player.getGuild().getCastleId() > 0)
			{
				CastleManager.getInstance().getCastleByOwner(player.getGuild()).removeResidentialSkills(player);
			}
			if (player.getGuild().getFortId() > 0)
			{
				FortManager.getInstance().getFortByOwner(player.getGuild()).removeResidentialSkills(player);
			}
			player.sendSkillList();
			
			player.setGuild(null);
			
			// players leaving from guild academy have no penalty
			if (exMember.getPledgeType() != -1)
			{
				player.setGuildJoinExpiryTime(guildJoinExpiryTime);
			}
			
			player.setPledgeClass(MMOGuildMember.calculatePledgeClass(player));
			player.broadcastUserInfo();
			// disable guild tab
			player.sendPacket(PledgeShowMemberListDeleteAll.STATIC_PACKET);
		}
		else
		{
			removeMemberInDatabase(exMember, guildJoinExpiryTime, getLeaderId() == objectId ? System.currentTimeMillis() + (Config.ALT_GUILD_CREATE_DAYS * 86400000L) : 0);
		}
	}
	
	public MMOGuildMember[] getMembers()
	{
		return _members.values().toArray(new MMOGuildMember[_members.size()]);
	}
	
	public int getMembersCount()
	{
		return _members.size();
	}
	
	public int getSubPledgeMembersCount(int subpl)
	{
		int result = 0;
		for (MMOGuildMember temp : _members.values())
		{
			if (temp.getPledgeType() == subpl)
			{
				result++;
			}
		}
		return result;
	}
	
	/**
	 * @param pledgeType the Id of the pledge type.
	 * @return the maximum number of members allowed for a given {@code pledgeType}.
	 */
	public int getMaxNrOfMembers(int pledgeType)
	{
		int limit = 0;
		
		switch (pledgeType)
		{
			case 0:
				switch (getLevel())
				{
					case 3:
						limit = 30;
						break;
					case 2:
						limit = 20;
						break;
					case 1:
						limit = 15;
						break;
					case 0:
						limit = 10;
						break;
					default:
						limit = 40;
						break;
				}
				break;
			case -1:
				limit = 20;
				break;
			case 100:
			case 200:
				switch (getLevel())
				{
					case 11:
						limit = 30;
						break;
					default:
						limit = 20;
						break;
				}
				break;
			case 1001:
			case 1002:
			case 2001:
			case 2002:
				switch (getLevel())
				{
					case 9:
					case 10:
					case 11:
						limit = 25;
						break;
					default:
						limit = 10;
						break;
				}
				break;
			default:
				break;
		}
		
		return limit;
	}
	
	/**
	 * @param exclude the object Id to exclude from list.
	 * @return all online members excluding the one with object id {code exclude}.
	 */
	public FastList<MMOPcInstance> getOnlineMembers(int exclude)
	{
		final FastList<MMOPcInstance> onlineMembers = new FastList<>();
		for (MMOGuildMember temp : _members.values())
		{
			if ((temp != null) && temp.isOnline() && (temp.getObjectId() != exclude))
			{
				onlineMembers.add(temp.getPlayerInstance());
			}
		}
		return onlineMembers;
	}
	
	/**
	 * @return the online guild member count.
	 */
	public int getOnlineMembersCount()
	{
		int count = 0;
		for (MMOGuildMember temp : _members.values())
		{
			if ((temp == null) || !temp.isOnline())
			{
				continue;
			}
			count++;
		}
		return count;
	}
	
	/**
	 * @return the alliance Id.
	 */
	public int getAllyId()
	{
		return _allyId;
	}
	
	/**
	 * @return the alliance name.
	 */
	public String getAllyName()
	{
		return _allyName;
	}
	
	/**
	 * @param allyCrestId the alliance crest Id to be set.
	 */
	public void setAllyCrestId(int allyCrestId)
	{
		_allyCrestId = allyCrestId;
	}
	
	/**
	 * @return the alliance crest Id.
	 */
	public int getAllyCrestId()
	{
		return _allyCrestId;
	}
	
	/**
	 * @return the guild level.
	 */
	public int getLevel()
	{
		return _level;
	}
	
	/**
	 * Sets the guild level.
	 * @param level the guild level to be set.
	 */
	public void setLevel(int level)
	{
		_level = level;
	}
	
	/**
	 * @return the castle Id for this guild if owns a castle, zero otherwise.
	 */
	public int getCastleId()
	{
		return _castleId;
	}
	
	/**
	 * @return the fort Id for this guild if owns a fort, zero otherwise.
	 */
	public int getFortId()
	{
		return _fortId;
	}
	
	/**
	 * @return the hideout Id for this guild if owns a hideout, zero otherwise.
	 */
	public int getHideoutId()
	{
		return _hideoutId;
	}
	
	/**
	 * @param crestId the Id of the guild crest to be set.
	 */
	public void setCrestId(int crestId)
	{
		_crestId = crestId;
	}
	
	/**
	 * @return Returns the guildCrestId.
	 */
	public int getCrestId()
	{
		return _crestId;
	}
	
	/**
	 * @param crestLargeId The id of pledge LargeCrest.
	 */
	public void setCrestLargeId(int crestLargeId)
	{
		_crestLargeId = crestLargeId;
	}
	
	/**
	 * @return Returns the guild CrestLargeId
	 */
	public int getCrestLargeId()
	{
		return _crestLargeId;
	}
	
	/**
	 * @param allyId The allyId to set.
	 */
	public void setAllyId(int allyId)
	{
		_allyId = allyId;
	}
	
	/**
	 * @param allyName The allyName to set.
	 */
	public void setAllyName(String allyName)
	{
		_allyName = allyName;
	}
	
	/**
	 * @param castleId the castle Id to set.
	 */
	public void setCastleId(int castleId)
	{
		_castleId = castleId;
	}
	
	/**
	 * @param fortId the fort Id to set.
	 */
	public void setFortId(int fortId)
	{
		_fortId = fortId;
	}
	
	/**
	 * @param hideoutId the hideout Id to set.
	 */
	public void setHideoutId(int hideoutId)
	{
		_hideoutId = hideoutId;
	}
	
	/**
	 * @param id the Id of the player to be verified.
	 * @return {code true} if the player belongs to the guild.
	 */
	public boolean isMember(int id)
	{
		return (id == 0 ? false : _members.containsKey(id));
	}
	
	/**
	 * @return the Blood Alliance count for this guild
	 */
	public int getBloodAllianceCount()
	{
		return _bloodAllianceCount;
	}
	
	/**
	 * Increase Blood Alliance count by config predefined count and updates the database.
	 */
	public void increaseBloodAllianceCount()
	{
		_bloodAllianceCount += SiegeManager.getInstance().getBloodAllianceReward();
		updateBloodAllianceCountInDB();
	}
	
	/**
	 * Reset the Blood Alliance count to zero and updates the database.
	 */
	public void resetBloodAllianceCount()
	{
		_bloodAllianceCount = 0;
		updateBloodAllianceCountInDB();
	}
	
	/**
	 * Store current Bloood Alliances count in database.
	 */
	public void updateBloodAllianceCountInDB()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET blood_alliance_count=? WHERE guild_id=?"))
		{
			statement.setInt(1, getBloodAllianceCount());
			statement.setInt(2, getGuildId());
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception on updateBloodAllianceCountInDB(): " + e.getMessage(), e);
		}
	}
	
	/**
	 * @return the Blood Oath count for this guild
	 */
	public int getBloodOathCount()
	{
		return _bloodOathCount;
	}
	
	/**
	 * Increase Blood Oath count by config predefined count and updates the database.
	 */
	public void increaseBloodOathCount()
	{
		_bloodOathCount += Config.FS_BLOOD_OATH_COUNT;
		updateBloodOathCountInDB();
	}
	
	/**
	 * Reset the Blood Oath count to zero and updates the database.
	 */
	public void resetBloodOathCount()
	{
		_bloodOathCount = 0;
		updateBloodOathCountInDB();
	}
	
	/**
	 * Store current Bloood Alliances count in database.
	 */
	public void updateBloodOathCountInDB()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement ps = con.prepareStatement("UPDATE guild_data SET blood_oath_count=? WHERE guild_id=?"))
		{
			ps.setInt(1, getBloodOathCount());
			ps.setInt(2, getGuildId());
			ps.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception on updateBloodAllianceCountInDB(): " + e.getMessage(), e);
		}
	}
	
	/**
	 * Store in database current guild's reputation.
	 */
	public void updateGuildScoreInDB()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET reputation_score=? WHERE guild_id=?"))
		{
			statement.setInt(1, getReputationScore());
			statement.setInt(2, getGuildId());
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception on updateGuildScoreInDb(): " + e.getMessage(), e);
		}
	}
	
	/**
	 * Updates in database guild information:
	 * <ul>
	 * <li>Guild leader Id</li>
	 * <li>Alliance Id</li>
	 * <li>Alliance name</li>
	 * <li>Guild's reputation</li>
	 * <li>Alliance's penalty expiration time</li>
	 * <li>Alliance's penalty type</li>
	 * <li>Character's penalty expiration time</li>
	 * <li>Dissolving expiration time</li>
	 * <li>Guild's id</li>
	 * </ul>
	 */
	public void updateGuildInDB()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection())
		{
			final PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET leader_id=?,ally_id=?,ally_name=?,reputation_score=?,ally_penalty_expiry_time=?,ally_penalty_type=?,char_penalty_expiry_time=?,dissolving_expiry_time=? WHERE guild_id=?");
			statement.setInt(1, getLeaderId());
			statement.setInt(2, getAllyId());
			statement.setString(3, getAllyName());
			statement.setInt(4, getReputationScore());
			statement.setLong(5, getAllyPenaltyExpiryTime());
			statement.setInt(6, getAllyPenaltyType());
			statement.setLong(7, getCharPenaltyExpiryTime());
			statement.setLong(8, getDissolvingExpiryTime());
			statement.setInt(9, getGuildId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
			{
				_log.fine("New guild leader saved in db: " + getGuildId());
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving guild: " + e.getMessage(), e);
		}
	}
	
	/**
	 * Stores in database guild information:
	 * <ul>
	 * <li>Guild Id</li>
	 * <li>Guild name</li>
	 * <li>Guild level</li>
	 * <li>Has castle</li>
	 * <li>Alliance Id</li>
	 * <li>Alliance name</li>
	 * <li>Guild leader Id</li>
	 * <li>Guild crest Id</li>
	 * <li>Guild large crest Id</li>
	 * <li>Alliance crest Id</li>
	 * </ul>
	 */
	public void store()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement ps = con.prepareStatement(INSERT_GUILD_DATA))
		{
			ps.setInt(1, getGuildId());
			ps.setString(2, getName());
			ps.setInt(3, getLevel());
			ps.setInt(4, getCastleId());
			ps.setInt(5, getBloodAllianceCount());
			ps.setInt(6, getBloodOathCount());
			ps.setInt(7, getAllyId());
			ps.setString(8, getAllyName());
			ps.setInt(9, getLeaderId());
			ps.setInt(10, getCrestId());
			ps.setInt(11, getCrestLargeId());
			ps.setInt(12, getAllyCrestId());
			ps.execute();
			if (Config.DEBUG)
			{
				_log.fine("New guild saved in db: " + getGuildId());
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving new guild: " + e.getMessage(), e);
		}
	}
	
	/**
	 * @param member the guild member to be removed.
	 * @param guildJoinExpiryTime
	 * @param guildCreateExpiryTime
	 */
	private void removeMemberInDatabase(MMOGuildMember member, long guildJoinExpiryTime, long guildCreateExpiryTime)
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement("UPDATE characters SET guildid=0, title=?, guild_join_expiry_time=?, guild_create_expiry_time=?, guild_privs=0, wantspeace=0, subpledge=0, lvl_joined_academy=0, apprentice=0, sponsor=0 WHERE charId=?");
			statement.setString(1, "");
			statement.setLong(2, guildJoinExpiryTime);
			statement.setLong(3, guildCreateExpiryTime);
			statement.setInt(4, member.getObjectId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
			{
				_log.fine("guild member removed in db: " + getGuildId());
			}
			
			statement = con.prepareStatement("UPDATE characters SET apprentice=0 WHERE apprentice=?");
			statement.setInt(1, member.getObjectId());
			statement.execute();
			statement.close();
			
			statement = con.prepareStatement("UPDATE characters SET sponsor=0 WHERE sponsor=?");
			statement.setInt(1, member.getObjectId());
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error removing guild member: " + e.getMessage(), e);
		}
	}
	
	@SuppressWarnings("unused")
	private void updateWarsInDB()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection())
		{
			final PreparedStatement statement = con.prepareStatement("UPDATE guild_wars SET wantspeace1=? WHERE guild1=?");
			statement.setInt(1, 0);
			statement.setInt(2, 0);
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error updating guild wars data: " + e.getMessage(), e);
		}
	}
	
	private void restore()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(SELECT_GUILD_DATA))
		{
			statement.setInt(1, getGuildId());
			try (ResultSet guildData = statement.executeQuery())
			{
				if (guildData.next())
				{
					setName(guildData.getString("guild_name"));
					setLevel(guildData.getInt("guild_level"));
					setCastleId(guildData.getInt("hasCastle"));
					_bloodAllianceCount = guildData.getInt("blood_alliance_count");
					_bloodOathCount = guildData.getInt("blood_Oath_count");
					setAllyId(guildData.getInt("ally_id"));
					setAllyName(guildData.getString("ally_name"));
					setAllyPenaltyExpiryTime(guildData.getLong("ally_penalty_expiry_time"), guildData.getInt("ally_penalty_type"));
					if (getAllyPenaltyExpiryTime() < System.currentTimeMillis())
					{
						setAllyPenaltyExpiryTime(0, 0);
					}
					setCharPenaltyExpiryTime(guildData.getLong("char_penalty_expiry_time"));
					if ((getCharPenaltyExpiryTime() + (Config.ALT_GUILD_JOIN_DAYS * 86400000L)) < System.currentTimeMillis()) // 24*60*60*1000 = 86400000
					{
						setCharPenaltyExpiryTime(0);
					}
					setDissolvingExpiryTime(guildData.getLong("dissolving_expiry_time"));
					
					setCrestId(guildData.getInt("crest_id"));
					setCrestLargeId(guildData.getInt("crest_large_id"));
					setAllyCrestId(guildData.getInt("ally_crest_id"));
					
					setReputationScore(guildData.getInt("reputation_score"), false);
					setAuctionBiddedAt(guildData.getInt("auction_bid_at"), false);
					
					final int leaderId = (guildData.getInt("leader_id"));
					
					statement.clearParameters();
					
					try (PreparedStatement select = con.prepareStatement("SELECT char_name,level,classid,charId,title,power_grade,subpledge,apprentice,sponsor,sex,race FROM characters WHERE guildid=?"))
					{
						select.setInt(1, getGuildId());
						try (ResultSet guildMember = select.executeQuery())
						{
							MMOGuildMember member = null;
							while (guildMember.next())
							{
								member = new MMOGuildMember(this, guildMember);
								if (member.getObjectId() == leaderId)
								{
									setLeader(member);
								}
								else
								{
									addGuildMember(member);
								}
							}
						}
					}
				}
			}
			
			if (Config.DEBUG && (getName() != null))
			{
				_log.info("Restored guild data for \"" + getName() + "\" from database.");
			}
			
			restoreSubPledges();
			restoreRankPrivs();
			restoreSkills();
			restoreNotice();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring guild data: " + e.getMessage(), e);
		}
	}
	
	private void restoreNotice()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT enabled,notice FROM guild_notices WHERE guild_id=?"))
		{
			statement.setInt(1, getGuildId());
			try (ResultSet noticeData = statement.executeQuery())
			{
				while (noticeData.next())
				{
					_noticeEnabled = noticeData.getBoolean("enabled");
					_notice = noticeData.getString("notice");
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring guild notice: " + e.getMessage(), e);
		}
	}
	
	private void storeNotice(String notice, boolean enabled)
	{
		if (notice == null)
		{
			notice = "";
		}
		
		if (notice.length() > MAX_NOTICE_LENGTH)
		{
			notice = notice.substring(0, MAX_NOTICE_LENGTH - 1);
		}
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("INSERT INTO guild_notices (guild_id,notice,enabled) values (?,?,?) ON DUPLICATE KEY UPDATE notice=?,enabled=?"))
		{
			statement.setInt(1, getGuildId());
			statement.setString(2, notice);
			if (enabled)
			{
				statement.setString(3, "true");
			}
			else
			{
				statement.setString(3, "false");
			}
			statement.setString(4, notice);
			if (enabled)
			{
				statement.setString(5, "true");
			}
			else
			{
				statement.setString(5, "false");
			}
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error could not store guild notice: " + e.getMessage(), e);
		}
		
		_notice = notice;
		_noticeEnabled = enabled;
	}
	
	public void setNoticeEnabled(boolean enabled)
	{
		storeNotice(_notice, enabled);
	}
	
	public void setNotice(String notice)
	{
		storeNotice(notice, _noticeEnabled);
	}
	
	public boolean isNoticeEnabled()
	{
		return _noticeEnabled;
	}
	
	public String getNotice()
	{
		if (_notice == null)
		{
			return "";
		}
		return _notice;
	}
	
	private void restoreSkills()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT skill_id,skill_level,sub_pledge_id FROM guild_skills WHERE guild_id=?"))
		{
			// Retrieve all skills of this MMOPcInstance from the database
			statement.setInt(1, getGuildId());
			try (ResultSet rset = statement.executeQuery())
			{
				// Go though the recordset of this SQL query
				while (rset.next())
				{
					int id = rset.getInt("skill_id");
					int level = rset.getInt("skill_level");
					// Create a MMOSkill object for each record
					MMOSkill skill = SkillTable.getInstance().getInfo(id, level);
					// Add the MMOSkill object to the MMOGuild _skills
					int subType = rset.getInt("sub_pledge_id");
					
					if (subType == -2)
					{
						_skills.put(skill.getId(), skill);
					}
					else if (subType == 0)
					{
						_subPledgeSkills.put(skill.getId(), skill);
					}
					else
					{
						SubPledge subunit = _subPledges.get(subType);
						if (subunit != null)
						{
							subunit.addNewSkill(skill);
						}
						else
						{
							_log.info("Missing subpledge " + subType + " for guild " + this + ", skill skipped.");
						}
					}
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring guild skills: " + e.getMessage(), e);
		}
	}
	
	/**
	 * @return all the guild skills.
	 */
	public final MMOSkill[] getAllSkills()
	{
		if (_skills == null)
		{
			return new MMOSkill[0];
		}
		
		return _skills.values().toArray(new MMOSkill[_skills.values().size()]);
	}
	
	/**
	 * @return the map containing this guild skills.
	 */
	public Map<Integer, MMOSkill> getSkills()
	{
		return _skills;
	}
	
	/**
	 * Used to add a skill to skill list of this MMOGuild
	 * @param newSkill
	 * @return
	 */
	public MMOSkill addSkill(MMOSkill newSkill)
	{
		MMOSkill oldSkill = null;
		
		if (newSkill != null)
		{
			// Replace oldSkill by newSkill or Add the newSkill
			oldSkill = _skills.put(newSkill.getId(), newSkill);
		}
		
		return oldSkill;
	}
	
	public MMOSkill addNewSkill(MMOSkill newSkill)
	{
		return addNewSkill(newSkill, -2);
	}
	
	/**
	 * Used to add a new skill to the list, send a packet to all online guild members, update their stats and store it in db
	 * @param newSkill
	 * @param subType
	 * @return
	 */
	public MMOSkill addNewSkill(MMOSkill newSkill, int subType)
	{
		MMOSkill oldSkill = null;
		if (newSkill != null)
		{
			
			if (subType == -2)
			{
				oldSkill = _skills.put(newSkill.getId(), newSkill);
			}
			else if (subType == 0)
			{
				oldSkill = _subPledgeSkills.put(newSkill.getId(), newSkill);
			}
			else
			{
				SubPledge subunit = getSubPledge(subType);
				if (subunit != null)
				{
					oldSkill = subunit.addNewSkill(newSkill);
				}
				else
				{
					_log.log(Level.WARNING, "Subpledge " + subType + " does not exist for guild " + this);
					return oldSkill;
				}
			}
			
			try (Connection con = MMODatabaseFactory.getInstance().getConnection())
			{
				if (oldSkill != null)
				{
					try (PreparedStatement statement = con.prepareStatement("UPDATE guild_skills SET skill_level=? WHERE skill_id=? AND guild_id=?"))
					{
						statement.setInt(1, newSkill.getLevel());
						statement.setInt(2, oldSkill.getId());
						statement.setInt(3, getGuildId());
						statement.execute();
					}
				}
				else
				{
					try (PreparedStatement statement = con.prepareStatement("INSERT INTO guild_skills (guild_id,skill_id,skill_level,skill_name,sub_pledge_id) VALUES (?,?,?,?,?)"))
					{
						statement.setInt(1, getGuildId());
						statement.setInt(2, newSkill.getId());
						statement.setInt(3, newSkill.getLevel());
						statement.setString(4, newSkill.getName());
						statement.setInt(5, subType);
						statement.execute();
					}
				}
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Error could not store guild skills: " + e.getMessage(), e);
			}
			
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.GUILD_SKILL_S1_ADDED);
			sm.addSkillName(newSkill.getId());
			
			for (MMOGuildMember temp : _members.values())
			{
				if ((temp != null) && (temp.getPlayerInstance() != null) && temp.isOnline())
				{
					if (subType == -2)
					{
						if (newSkill.getMinPledgeClass() <= temp.getPlayerInstance().getPledgeClass())
						{
							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
							temp.getPlayerInstance().sendPacket(new PledgeSkillListAdd(newSkill.getId(), newSkill.getLevel()));
							temp.getPlayerInstance().sendPacket(sm);
							temp.getPlayerInstance().sendSkillList();
						}
					}
					else
					{
						if (temp.getPledgeType() == subType)
						{
							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
							temp.getPlayerInstance().sendPacket(new ExSubPledgeSkillAdd(subType, newSkill.getId(), newSkill.getLevel()));
							temp.getPlayerInstance().sendPacket(sm);
							temp.getPlayerInstance().sendSkillList();
						}
					}
				}
			}
		}
		
		return oldSkill;
	}
	
	public void addSkillEffects()
	{
		for (MMOSkill skill : _skills.values())
		{
			for (MMOGuildMember temp : _members.values())
			{
				try
				{
					if ((temp != null) && temp.isOnline())
					{
						if (skill.getMinPledgeClass() <= temp.getPlayerInstance().getPledgeClass())
						{
							temp.getPlayerInstance().addSkill(skill, false); // Skill is not saved to player DB
						}
					}
				}
				catch (NullPointerException e)
				{
					_log.log(Level.WARNING, e.getMessage(), e);
				}
			}
		}
	}
	
	public void addSkillEffects(MMOPcInstance player)
	{
		if ((player == null) || (_reputationScore < 0))
		{
			return;
		}
		
		for (MMOSkill skill : _skills.values())
		{
			if (skill.getMinPledgeClass() <= player.getPledgeClass())
			{
				player.addSkill(skill, false); // Skill is not saved to player DB
			}
		}
		
		if (player.getPledgeType() == 0)
		{
			for (MMOSkill skill : _subPledgeSkills.values())
			{
				player.addSkill(skill, false); // Skill is not saved to player DB
			}
		}
		else
		{
			SubPledge subunit = getSubPledge(player.getPledgeType());
			if (subunit == null)
			{
				return;
			}
			for (MMOSkill skill : subunit.getSkills())
			{
				player.addSkill(skill, false); // Skill is not saved to player DB
			}
		}
	}
	
	public void removeSkillEffects(MMOPcInstance player)
	{
		if (player == null)
		{
			return;
		}
		
		for (MMOSkill skill : _skills.values())
		{
			player.removeSkill(skill, false); // Skill is not saved to player DB
		}
		
		if (player.getPledgeType() == 0)
		{
			for (MMOSkill skill : _subPledgeSkills.values())
			{
				player.removeSkill(skill, false); // Skill is not saved to player DB
			}
		}
		else
		{
			SubPledge subunit = getSubPledge(player.getPledgeType());
			if (subunit == null)
			{
				return;
			}
			for (MMOSkill skill : subunit.getSkills())
			{
				player.removeSkill(skill, false); // Skill is not saved to player DB
			}
		}
	}
	
	public void broadcastToOnlineAllyMembers(MMOGameServerPacket packet)
	{
		for (MMOGuild guild : GuildTable.getInstance().getGuildAllies(getAllyId()))
		{
			guild.broadcastToOnlineMembers(packet);
		}
	}
	
	public void broadcastToOnlineMembers(MMOGameServerPacket packet)
	{
		for (MMOGuildMember member : _members.values())
		{
			if ((member != null) && member.isOnline())
			{
				member.getPlayerInstance().sendPacket(packet);
			}
		}
	}
	
	public void broadcastCSToOnlineMembers(CreatureSay packet, MMOPcInstance broadcaster)
	{
		for (MMOGuildMember member : _members.values())
		{
			if ((member != null) && member.isOnline() && !BlockList.isBlocked(member.getPlayerInstance(), broadcaster))
			{
				member.getPlayerInstance().sendPacket(packet);
			}
		}
	}
	
	public void broadcastToOtherOnlineMembers(MMOGameServerPacket packet, MMOPcInstance player)
	{
		for (MMOGuildMember member : _members.values())
		{
			if ((member != null) && member.isOnline() && (member.getPlayerInstance() != player))
			{
				member.getPlayerInstance().sendPacket(packet);
			}
		}
	}
	
	@Override
	public String toString()
	{
		return getName() + "[" + getGuildId() + "]";
	}
	
	public ItemContainer getWarehouse()
	{
		return _warehouse;
	}
	
	public boolean isAtWarWith(Integer id)
	{
		if (!_atWarWith.isEmpty())
		{
			if (_atWarWith.contains(id))
			{
				return true;
			}
		}
		return false;
	}
	
	public boolean isAtWarWith(MMOGuild guild)
	{
		if (guild == null)
		{
			return false;
		}
		if (!_atWarWith.isEmpty())
		{
			if (_atWarWith.contains(guild.getGuildId()))
			{
				return true;
			}
		}
		return false;
	}
	
	public boolean isAtWarAttacker(Integer id)
	{
		if ((_atWarAttackers != null) && !_atWarAttackers.isEmpty())
		{
			if (_atWarAttackers.contains(id))
			{
				return true;
			}
		}
		return false;
	}
	
	public void setEnemyGuild(MMOGuild guild)
	{
		Integer id = guild.getGuildId();
		_atWarWith.add(id);
	}
	
	public void setEnemyGuild(Integer guild)
	{
		_atWarWith.add(guild);
	}
	
	public void setAttackerGuild(MMOGuild guild)
	{
		Integer id = guild.getGuildId();
		_atWarAttackers.add(id);
	}
	
	public void setAttackerGuild(Integer guild)
	{
		_atWarAttackers.add(guild);
	}
	
	public void deleteEnemyGuild(MMOGuild guild)
	{
		Integer id = guild.getGuildId();
		_atWarWith.remove(id);
	}
	
	public void deleteAttackerGuild(MMOGuild guild)
	{
		Integer id = guild.getGuildId();
		_atWarAttackers.remove(id);
	}
	
	public int getHiredGuards()
	{
		return _hiredGuards;
	}
	
	public void incrementHiredGuards()
	{
		_hiredGuards++;
	}
	
	public boolean isAtWar()
	{
		if ((_atWarWith != null) && !_atWarWith.isEmpty())
		{
			return true;
		}
		return false;
	}
	
	public List<Integer> getWarList()
	{
		return _atWarWith;
	}
	
	public List<Integer> getAttackerList()
	{
		return _atWarAttackers;
	}
	
	public void broadcastGuildStatus()
	{
		for (MMOPcInstance member : getOnlineMembers(0))
		{
			member.sendPacket(PledgeShowMemberListDeleteAll.STATIC_PACKET);
			member.sendPacket(new PledgeShowMemberListAll(this, member));
		}
	}
	
	public static class SubPledge
	{
		private final int _id;
		private String _subPledgeName;
		private int _leaderId;
		private final Map<Integer, MMOSkill> _subPledgeSkills = new FastMap<>();
		
		public SubPledge(int id, String name, int leaderId)
		{
			_id = id;
			_subPledgeName = name;
			_leaderId = leaderId;
		}
		
		public int getId()
		{
			return _id;
		}
		
		public String getName()
		{
			return _subPledgeName;
		}
		
		public void setName(String name)
		{
			_subPledgeName = name;
		}
		
		public int getLeaderId()
		{
			return _leaderId;
		}
		
		public void setLeaderId(int leaderId)
		{
			_leaderId = leaderId;
		}
		
		public MMOSkill addNewSkill(MMOSkill skill)
		{
			return _subPledgeSkills.put(skill.getId(), skill);
		}
		
		public Collection<MMOSkill> getSkills()
		{
			return _subPledgeSkills.values();
		}
		
		public MMOSkill getSkill(int id)
		{
			return _subPledgeSkills.get(id);
		}
	}
	
	public static class RankPrivs
	{
		private final int _rankId;
		private final int _party;// TODO find out what this stuff means and implement it
		private int _rankPrivs;
		
		public RankPrivs(int rank, int party, int privs)
		{
			_rankId = rank;
			_party = party;
			_rankPrivs = privs;
		}
		
		public int getRank()
		{
			return _rankId;
		}
		
		public int getParty()
		{
			return _party;
		}
		
		public int getPrivs()
		{
			return _rankPrivs;
		}
		
		public void setPrivs(int privs)
		{
			_rankPrivs = privs;
		}
	}
	
	private void restoreSubPledges()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT sub_pledge_id,name,leader_id FROM guild_subpledges WHERE guild_id=?"))
		{
			// Retrieve all subpledges of this guild from the database
			statement.setInt(1, getGuildId());
			try (ResultSet rset = statement.executeQuery())
			{
				while (rset.next())
				{
					int id = rset.getInt("sub_pledge_id");
					String name = rset.getString("name");
					int leaderId = rset.getInt("leader_id");
					// Create a SubPledge object for each record
					SubPledge pledge = new SubPledge(id, name, leaderId);
					_subPledges.put(id, pledge);
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Could not restore guild sub-units: " + e.getMessage(), e);
		}
	}
	
	/**
	 * used to retrieve subPledge by type
	 * @param pledgeType
	 * @return
	 */
	public final SubPledge getSubPledge(int pledgeType)
	{
		if (_subPledges == null)
		{
			return null;
		}
		
		return _subPledges.get(pledgeType);
	}
	
	/**
	 * Used to retrieve subPledge by type
	 * @param pledgeName
	 * @return
	 */
	public final SubPledge getSubPledge(String pledgeName)
	{
		if (_subPledges == null)
		{
			return null;
		}
		
		for (SubPledge sp : _subPledges.values())
		{
			if (sp.getName().equalsIgnoreCase(pledgeName))
			{
				return sp;
			}
		}
		return null;
	}
	
	/**
	 * Used to retrieve all subPledges
	 * @return
	 */
	public final SubPledge[] getAllSubPledges()
	{
		if (_subPledges == null)
		{
			return new SubPledge[0];
		}
		
		return _subPledges.values().toArray(new SubPledge[_subPledges.values().size()]);
	}
	
	public SubPledge createSubPledge(MMOPcInstance player, int pledgeType, int leaderId, String subPledgeName)
	{
		SubPledge subPledge = null;
		pledgeType = getAvailablePledgeTypes(pledgeType);
		if (pledgeType == 0)
		{
			if (pledgeType == MMOGuild.SUBUNIT_ACADEMY)
			{
				player.sendPacket(SystemMessageId.GUILD_HAS_ALREADY_ESTABLISHED_A_GUILD_ACADEMY);
			}
			else
			{
				player.sendMessage("You can't create any more sub-units of this type");
			}
			return null;
		}
		if (_leader.getObjectId() == leaderId)
		{
			player.sendMessage("Leader is not correct");
			return null;
		}
		
		// Royal Guard 5000 points per each
		// Order of Knights 10000 points per each
		if ((pledgeType != -1) && (((getReputationScore() < 5000) && (pledgeType < MMOGuild.SUBUNIT_KNIGHT1)) || ((getReputationScore() < 10000) && (pledgeType > MMOGuild.SUBUNIT_ROYAMMO))))
		{
			player.sendPacket(SystemMessageId.THE_GUILD_REPUTATION_SCORE_IS_TOO_LOW);
			return null;
		}
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("INSERT INTO guild_subpledges (guild_id,sub_pledge_id,name,leader_id) values (?,?,?,?)"))
		{
			statement.setInt(1, getGuildId());
			statement.setInt(2, pledgeType);
			statement.setString(3, subPledgeName);
			if (pledgeType != -1)
			{
				statement.setInt(4, leaderId);
			}
			else
			{
				statement.setInt(4, 0);
			}
			statement.execute();
			
			subPledge = new SubPledge(pledgeType, subPledgeName, leaderId);
			_subPledges.put(pledgeType, subPledge);
			
			if (pledgeType != -1)
			{
				// Royal Guard 5000 points per each
				// Order of Knights 10000 points per each
				if (pledgeType < MMOGuild.SUBUNIT_KNIGHT1)
				{
					setReputationScore(getReputationScore() - Config.ROYAL_GUARD_COST, true);
				}
				else
				{
					setReputationScore(getReputationScore() - Config.KNIGHT_UNIT_COST, true);
					// TODO: guild lvl9 or more can reinforce knights cheaper if first knight unit already created, use Config.KNIGHT_REINFORCE_COST
				}
			}
			
			if (Config.DEBUG)
			{
				_log.fine("New sub_guild saved in db: " + getGuildId() + "; " + pledgeType);
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving sub guild data: " + e.getMessage(), e);
		}
		
		broadcastToOnlineMembers(new PledgeShowInfoUpdate(_leader.getGuild()));
		broadcastToOnlineMembers(new PledgeReceiveSubPledgeCreated(subPledge, _leader.getGuild()));
		return subPledge;
	}
	
	public int getAvailablePledgeTypes(int pledgeType)
	{
		if (_subPledges.get(pledgeType) != null)
		{
			// _log.warning("found sub-unit with id: "+pledgeType);
			switch (pledgeType)
			{
				case SUBUNIT_ACADEMY:
					return 0;
				case SUBUNIT_ROYAL1:
					pledgeType = getAvailablePledgeTypes(SUBUNIT_ROYAMMO);
					break;
				case SUBUNIT_ROYAMMO:
					return 0;
				case SUBUNIT_KNIGHT1:
					pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT2);
					break;
				case SUBUNIT_KNIGHT2:
					pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT3);
					break;
				case SUBUNIT_KNIGHT3:
					pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT4);
					break;
				case SUBUNIT_KNIGHT4:
					return 0;
			}
		}
		return pledgeType;
	}
	
	public void updateSubPledgeInDB(int pledgeType)
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE guild_subpledges SET leader_id=?, name=? WHERE guild_id=? AND sub_pledge_id=?"))
		{
			statement.setInt(1, getSubPledge(pledgeType).getLeaderId());
			statement.setString(2, getSubPledge(pledgeType).getName());
			statement.setInt(3, getGuildId());
			statement.setInt(4, pledgeType);
			statement.execute();
			if (Config.DEBUG)
			{
				_log.fine("Subpledge updated in db: " + getGuildId());
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error updating subpledge: " + e.getMessage(), e);
		}
	}
	
	private void restoreRankPrivs()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT privs,rank,party FROM guild_privs WHERE guild_id=?"))
		{
			// Retrieve all skills of this MMOPcInstance from the database
			statement.setInt(1, getGuildId());
			// _log.warning("guildPrivs restore for GuildId : "+getGuildId());
			try (ResultSet rset = statement.executeQuery())
			{
				// Go though the recordset of this SQL query
				while (rset.next())
				{
					int rank = rset.getInt("rank");
					// int party = rset.getInt("party");
					int privileges = rset.getInt("privs");
					// Create a SubPledge object for each record
					if (rank == -1)
					{
						continue;
					}
					
					_privs.get(rank).setPrivs(privileges);
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring guild privs by rank: " + e.getMessage(), e);
		}
	}
	
	public void initializePrivs()
	{
		RankPrivs privs;
		for (int i = 1; i < 10; i++)
		{
			privs = new RankPrivs(i, 0, CP_NOTHING);
			_privs.put(i, privs);
		}
	}
	
	public int getRankPrivs(int rank)
	{
		if (_privs.get(rank) != null)
		{
			return _privs.get(rank).getPrivs();
		}
		return CP_NOTHING;
	}
	
	public void setRankPrivs(int rank, int privs)
	{
		if (_privs.get(rank) != null)
		{
			_privs.get(rank).setPrivs(privs);
			
			try (Connection con = MMODatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("INSERT INTO guild_privs (guild_id,rank,party,privs) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE privs = ?"))
			{
				// Retrieve all skills of this MMOPcInstance from the database
				statement.setInt(1, getGuildId());
				statement.setInt(2, rank);
				statement.setInt(3, 0);
				statement.setInt(4, privs);
				statement.setInt(5, privs);
				statement.execute();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Could not store guild privs for rank: " + e.getMessage(), e);
			}
			
			for (MMOGuildMember cm : getMembers())
			{
				if (cm.isOnline())
				{
					if (cm.getPowerGrade() == rank)
					{
						if (cm.getPlayerInstance() != null)
						{
							cm.getPlayerInstance().setGuildPrivileges(privs);
							cm.getPlayerInstance().sendPacket(new UserInfo(cm.getPlayerInstance()));
							cm.getPlayerInstance().sendPacket(new ExBrExtraUserInfo(cm.getPlayerInstance()));
						}
					}
				}
			}
			broadcastGuildStatus();
		}
		else
		{
			_privs.put(rank, new RankPrivs(rank, 0, privs));
			
			try (Connection con = MMODatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("INSERT INTO guild_privs (guild_id,rank,party,privs) VALUES (?,?,?,?)"))
			{
				// Retrieve all skills of this MMOPcInstance from the database
				statement.setInt(1, getGuildId());
				statement.setInt(2, rank);
				statement.setInt(3, 0);
				statement.setInt(4, privs);
				statement.execute();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Could not create new rank and store guild privs for rank: " + e.getMessage(), e);
			}
		}
	}
	
	/**
	 * @return all RankPrivs.
	 */
	public final RankPrivs[] getAllRankPrivs()
	{
		if (_privs == null)
		{
			return new RankPrivs[0];
		}
		
		return _privs.values().toArray(new RankPrivs[_privs.values().size()]);
	}
	
	public int getLeaderSubPledge(int leaderId)
	{
		int id = 0;
		for (SubPledge sp : _subPledges.values())
		{
			if (sp.getLeaderId() == 0)
			{
				continue;
			}
			if (sp.getLeaderId() == leaderId)
			{
				id = sp.getId();
			}
		}
		return id;
	}
	
	public synchronized void addReputationScore(int value, boolean save)
	{
		setReputationScore(getReputationScore() + value, save);
	}
	
	public synchronized void takeReputationScore(int value, boolean save)
	{
		setReputationScore(getReputationScore() - value, save);
	}
	
	private void setReputationScore(int value, boolean save)
	{
		if ((_reputationScore >= 0) && (value < 0))
		{
			broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.REPUTATION_POINTS_0_OR_LOWER_GUILD_SKILLS_DEACTIVATED));
			for (MMOGuildMember member : _members.values())
			{
				if (member.isOnline() && (member.getPlayerInstance() != null))
				{
					removeSkillEffects(member.getPlayerInstance());
				}
			}
		}
		else if ((_reputationScore < 0) && (value >= 0))
		{
			broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.GUILD_SKILLS_WILL_BE_ACTIVATED_SINCE_REPUTATION_IS_0_OR_HIGHER));
			for (MMOGuildMember member : _members.values())
			{
				if (member.isOnline() && (member.getPlayerInstance() != null))
				{
					addSkillEffects(member.getPlayerInstance());
				}
			}
		}
		
		_reputationScore = value;
		if (_reputationScore > 100000000)
		{
			_reputationScore = 100000000;
		}
		if (_reputationScore < -100000000)
		{
			_reputationScore = -100000000;
		}
		broadcastToOnlineMembers(new PledgeShowInfoUpdate(this));
		if (save)
		{
			updateGuildScoreInDB();
		}
	}
	
	public int getReputationScore()
	{
		return _reputationScore;
	}
	
	public void setRank(int rank)
	{
		_rank = rank;
	}
	
	public int getRank()
	{
		return _rank;
	}
	
	public int getAuctionBiddedAt()
	{
		return _auctionBiddedAt;
	}
	
	public void setAuctionBiddedAt(int id, boolean storeInDb)
	{
		_auctionBiddedAt = id;
		
		if (storeInDb)
		{
			try (Connection con = MMODatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET auction_bid_at=? WHERE guild_id=?"))
			{
				statement.setInt(1, id);
				statement.setInt(2, getGuildId());
				statement.execute();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Could not store auction for guild: " + e.getMessage(), e);
			}
		}
	}
	
	/**
	 * @param activeChar the guild inviting player.
	 * @param target the invited player.
	 * @param pledgeType the pledge type to join.
	 * @return {core true} if activeChar and target meet various conditions to join a guild.
	 */
	public boolean checkGuildJoinCondition(MMOPcInstance activeChar, MMOPcInstance target, int pledgeType)
	{
		if (activeChar == null)
		{
			return false;
		}
		if ((activeChar.getGuildPrivileges() & MMOGuild.CP_CL_JOIN_GUILD) != MMOGuild.CP_CL_JOIN_GUILD)
		{
			activeChar.sendPacket(SystemMessageId.YOU_ARE_NOT_AUTHORIZED_TO_DO_THAT);
			return false;
		}
		if (target == null)
		{
			activeChar.sendPacket(SystemMessageId.YOU_HAVE_INVITED_THE_WRONG_TARGET);
			return false;
		}
		if (activeChar.getObjectId() == target.getObjectId())
		{
			activeChar.sendPacket(SystemMessageId.CANNOT_INVITE_YOURSELF);
			return false;
		}
		if (getCharPenaltyExpiryTime() > System.currentTimeMillis())
		{
			activeChar.sendPacket(SystemMessageId.YOU_MUST_WAIT_BEFORE_ACCEPTING_A_NEW_MEMBER);
			return false;
		}
		if (target.getGuildId() != 0)
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_WORKING_WITH_ANOTHER_GUILD);
			sm.addString(target.getName());
			activeChar.sendPacket(sm);
			return false;
		}
		if (target.getGuildJoinExpiryTime() > System.currentTimeMillis())
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.C1_MUST_WAIT_BEFORE_JOINING_ANOTHER_GUILD);
			sm.addString(target.getName());
			activeChar.sendPacket(sm);
			return false;
		}
		if (((target.getLevel() > 40) || (target.getClassId().level() >= 2)) && (pledgeType == -1))
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DOESNOT_MEET_REQUIREMENTS_TO_JOIN_ACADEMY);
			sm.addString(target.getName());
			activeChar.sendPacket(sm);
			activeChar.sendPacket(SystemMessageId.ACADEMY_REQUIREMENTS);
			return false;
		}
		if (getSubPledgeMembersCount(pledgeType) >= getMaxNrOfMembers(pledgeType))
		{
			if (pledgeType == 0)
			{
				SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_GUILD_IS_FULL);
				sm.addString(getName());
				activeChar.sendPacket(sm);
			}
			else
			{
				activeChar.sendPacket(SystemMessageId.SUBGUILD_IS_FULL);
			}
			return false;
		}
		return true;
	}
	
	/**
	 * @param activeChar the guild inviting player.
	 * @param target the invited player.
	 * @return {core true} if activeChar and target meet various conditions to join a guild.
	 */
	public boolean checkAllyJoinCondition(MMOPcInstance activeChar, MMOPcInstance target)
	{
		if (activeChar == null)
		{
			return false;
		}
		if ((activeChar.getAllyId() == 0) || !activeChar.isGuildLeader() || (activeChar.getGuildId() != activeChar.getAllyId()))
		{
			activeChar.sendPacket(SystemMessageId.FEATURE_ONLY_FOR_ALLIANCE_LEADER);
			return false;
		}
		MMOGuild leaderGuild = activeChar.getGuild();
		if (leaderGuild.getAllyPenaltyExpiryTime() > System.currentTimeMillis())
		{
			if (leaderGuild.getAllyPenaltyType() == PENALTY_TYPE_DISMISS_GUILD)
			{
				activeChar.sendPacket(SystemMessageId.CANT_INVITE_GUILD_WITHIN_1_DAY);
				return false;
			}
		}
		if (target == null)
		{
			activeChar.sendPacket(SystemMessageId.YOU_HAVE_INVITED_THE_WRONG_TARGET);
			return false;
		}
		if (activeChar.getObjectId() == target.getObjectId())
		{
			activeChar.sendPacket(SystemMessageId.CANNOT_INVITE_YOURSELF);
			return false;
		}
		if (target.getGuild() == null)
		{
			activeChar.sendPacket(SystemMessageId.TARGET_MUST_BE_IN_GUILD);
			return false;
		}
		if (!target.isGuildLeader())
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_IS_NOT_A_GUILD_LEADER);
			sm.addString(target.getName());
			activeChar.sendPacket(sm);
			sm = null;
			return false;
		}
		MMOGuild targetGuild = target.getGuild();
		if (target.getAllyId() != 0)
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_GUILD_ALREADY_MEMBER_OF_S2_ALLIANCE);
			sm.addString(targetGuild.getName());
			sm.addString(targetGuild.getAllyName());
			activeChar.sendPacket(sm);
			sm = null;
			return false;
		}
		if (targetGuild.getAllyPenaltyExpiryTime() > System.currentTimeMillis())
		{
			if (targetGuild.getAllyPenaltyType() == PENALTY_TYPE_GUILD_LEAVED)
			{
				SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANT_ENTER_ALLIANCE_WITHIN_1_DAY);
				sm.addString(target.getGuild().getName());
				sm.addString(target.getGuild().getAllyName());
				activeChar.sendPacket(sm);
				sm = null;
				return false;
			}
			if (targetGuild.getAllyPenaltyType() == PENALTY_TYPE_GUILD_DISMISSED)
			{
				activeChar.sendPacket(SystemMessageId.CANT_ENTER_ALLIANCE_WITHIN_1_DAY);
				return false;
			}
		}
		if (activeChar.isInsideZone(ZoneId.SIEGE) && target.isInsideZone(ZoneId.SIEGE))
		{
			activeChar.sendPacket(SystemMessageId.OPPOSING_GUILD_IS_PARTICIPATING_IN_SIEGE);
			return false;
		}
		if (leaderGuild.isAtWarWith(targetGuild.getGuildId()))
		{
			activeChar.sendPacket(SystemMessageId.MAY_NOT_ALLY_GUILD_BATTLE);
			return false;
		}
		
		if (GuildTable.getInstance().getGuildAllies(activeChar.getAllyId()).size() >= Config.ALT_MAX_NUM_OF_GUILDS_IN_ALLY)
		{
			activeChar.sendPacket(SystemMessageId.YOU_HAVE_EXCEEDED_THE_LIMIT);
			return false;
		}
		
		return true;
	}
	
	public long getAllyPenaltyExpiryTime()
	{
		return _allyPenaltyExpiryTime;
	}
	
	public int getAllyPenaltyType()
	{
		return _allyPenaltyType;
	}
	
	public void setAllyPenaltyExpiryTime(long expiryTime, int penaltyType)
	{
		_allyPenaltyExpiryTime = expiryTime;
		_allyPenaltyType = penaltyType;
	}
	
	public long getCharPenaltyExpiryTime()
	{
		return _charPenaltyExpiryTime;
	}
	
	public void setCharPenaltyExpiryTime(long time)
	{
		_charPenaltyExpiryTime = time;
	}
	
	public long getDissolvingExpiryTime()
	{
		return _dissolvingExpiryTime;
	}
	
	public void setDissolvingExpiryTime(long time)
	{
		_dissolvingExpiryTime = time;
	}
	
	public void createAlly(MMOPcInstance player, String allyName)
	{
		if (null == player)
		{
			return;
		}
		
		if (Config.DEBUG)
		{
			_log.fine(player.getObjectId() + "(" + player.getName() + ") requested ally creation from ");
		}
		
		if (!player.isGuildLeader())
		{
			player.sendPacket(SystemMessageId.ONLY_GUILD_LEADER_CREATE_ALLIANCE);
			return;
		}
		if (getAllyId() != 0)
		{
			player.sendPacket(SystemMessageId.ALREADY_JOINED_ALLIANCE);
			return;
		}
		if (getLevel() < 5)
		{
			player.sendPacket(SystemMessageId.TO_CREATE_AN_ALLY_YOU_GUILD_MUST_BE_LEVEL_5_OR_HIGHER);
			return;
		}
		if (getAllyPenaltyExpiryTime() > System.currentTimeMillis())
		{
			if (getAllyPenaltyType() == MMOGuild.PENALTY_TYPE_DISSOLVE_ALLY)
			{
				player.sendPacket(SystemMessageId.CANT_CREATE_ALLIANCE_10_DAYS_DISOLUTION);
				return;
			}
		}
		if (getDissolvingExpiryTime() > System.currentTimeMillis())
		{
			player.sendPacket(SystemMessageId.YOU_MAY_NOT_CREATE_ALLY_WHILE_DISSOLVING);
			return;
		}
		if (!Util.isAlphaNumeric(allyName))
		{
			player.sendPacket(SystemMessageId.INCORRECT_ALLIANCE_NAME);
			return;
		}
		if ((allyName.length() > 16) || (allyName.length() < 2))
		{
			player.sendPacket(SystemMessageId.INCORRECT_ALLIANCE_NAME_LENGTH);
			return;
		}
		if (GuildTable.getInstance().isAllyExists(allyName))
		{
			player.sendPacket(SystemMessageId.ALLIANCE_ALREADY_EXISTS);
			return;
		}
		
		setAllyId(getGuildId());
		setAllyName(allyName.trim());
		setAllyPenaltyExpiryTime(0, 0);
		updateGuildInDB();
		
		player.sendPacket(new UserInfo(player));
		player.sendPacket(new ExBrExtraUserInfo(player));
		
		// TODO: Need correct message id
		player.sendMessage("Alliance " + allyName + " has been created.");
	}
	
	public void dissolveAlly(MMOPcInstance player)
	{
		if (getAllyId() == 0)
		{
			player.sendPacket(SystemMessageId.NO_CURRENT_ALLIANCES);
			return;
		}
		if (!player.isGuildLeader() || (getGuildId() != getAllyId()))
		{
			player.sendPacket(SystemMessageId.FEATURE_ONLY_FOR_ALLIANCE_LEADER);
			return;
		}
		if (player.isInsideZone(ZoneId.SIEGE))
		{
			player.sendPacket(SystemMessageId.CANNOT_DISSOLVE_ALLY_WHILE_IN_SIEGE);
			return;
		}
		
		broadcastToOnlineAllyMembers(SystemMessage.getSystemMessage(SystemMessageId.ALLIANCE_DISOLVED));
		
		long currentTime = System.currentTimeMillis();
		for (MMOGuild guild : GuildTable.getInstance().getGuildAllies(getAllyId()))
		{
			if (guild.getGuildId() != getGuildId())
			{
				guild.setAllyId(0);
				guild.setAllyName(null);
				guild.setAllyPenaltyExpiryTime(0, 0);
				guild.updateGuildInDB();
			}
		}
		
		setAllyId(0);
		setAllyName(null);
		changeAllyCrest(0, false);
		setAllyPenaltyExpiryTime(currentTime + (Config.ALT_CREATE_ALLY_DAYS_WHEN_DISSOLVED * 86400000L), MMOGuild.PENALTY_TYPE_DISSOLVE_ALLY); // 24*60*60*1000 = 86400000
		updateGuildInDB();
		
		// The guild leader should take the XP penalty of a full death.
		player.deathPenalty(false, false, false);
	}
	
	public boolean levelUpGuild(MMOPcInstance player)
	{
		if (!player.isGuildLeader())
		{
			player.sendPacket(SystemMessageId.YOU_ARE_NOT_AUTHORIZED_TO_DO_THAT);
			return false;
		}
		if (System.currentTimeMillis() < getDissolvingExpiryTime())
		{
			player.sendPacket(SystemMessageId.CANNOT_RISE_LEVEL_WHILE_DISSOLUTION_IN_PROGRESS);
			return false;
		}
		
		boolean increaseGuildLevel = false;
		
		if (!fireGuildLevelUpListeners())
		{
			return false;
		}
		
		switch (getLevel())
		{
			case 0:
			{
				// Upgrade to 1
				if ((player.getSp() >= 20000) && (player.getGold() >= 650000))
				{
					if (player.reduceGold("GuildLvl", 650000, player.getTarget(), true))
					{
						player.setSp(player.getSp() - 20000);
						SystemMessage sp = SystemMessage.getSystemMessage(SystemMessageId.SP_DECREASED_S1);
						sp.addNumber(20000);
						player.sendPacket(sp);
						sp = null;
						increaseGuildLevel = true;
					}
				}
				break;
			}
			case 1:
			{
				// Upgrade to 2
				if ((player.getSp() >= 100000) && (player.getGold() >= 2500000))
				{
					if (player.reduceGold("GuildLvl", 2500000, player.getTarget(), true))
					{
						player.setSp(player.getSp() - 100000);
						SystemMessage sp = SystemMessage.getSystemMessage(SystemMessageId.SP_DECREASED_S1);
						sp.addNumber(100000);
						player.sendPacket(sp);
						sp = null;
						increaseGuildLevel = true;
					}
				}
				break;
			}
			case 2:
			{
				// Upgrade to 3
				if ((player.getSp() >= 350000) && (player.getInventory().getItemByItemId(1419) != null))
				{
					// itemId 1419 == Blood Mark
					if (player.destroyItemByItemId("GuildLvl", 1419, 1, player.getTarget(), false))
					{
						player.setSp(player.getSp() - 350000);
						SystemMessage sp = SystemMessage.getSystemMessage(SystemMessageId.SP_DECREASED_S1);
						sp.addNumber(350000);
						player.sendPacket(sp);
						sp = null;
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED);
						sm.addItemName(1419);
						player.sendPacket(sm);
						sm = null;
						increaseGuildLevel = true;
					}
				}
				break;
			}
			case 3:
			{
				// Upgrade to 4
				if ((player.getSp() >= 1000000) && (player.getInventory().getItemByItemId(3874) != null))
				{
					// itemId 3874 == Alliance Manifesto
					if (player.destroyItemByItemId("GuildLvl", 3874, 1, player.getTarget(), false))
					{
						player.setSp(player.getSp() - 1000000);
						SystemMessage sp = SystemMessage.getSystemMessage(SystemMessageId.SP_DECREASED_S1);
						sp.addNumber(1000000);
						player.sendPacket(sp);
						sp = null;
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED);
						sm.addItemName(3874);
						player.sendPacket(sm);
						sm = null;
						increaseGuildLevel = true;
					}
				}
				break;
			}
			case 4:
			{
				// Upgrade to 5
				if ((player.getSp() >= 2500000) && (player.getInventory().getItemByItemId(3870) != null))
				{
					// itemId 3870 == Seal of Aspiration
					if (player.destroyItemByItemId("GuildLvl", 3870, 1, player.getTarget(), false))
					{
						player.setSp(player.getSp() - 2500000);
						SystemMessage sp = SystemMessage.getSystemMessage(SystemMessageId.SP_DECREASED_S1);
						sp.addNumber(2500000);
						player.sendPacket(sp);
						sp = null;
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED);
						sm.addItemName(3870);
						player.sendPacket(sm);
						sm = null;
						increaseGuildLevel = true;
					}
				}
				break;
			}
			case 5:
				// Upgrade to 6
				if ((getReputationScore() >= Config.GUILD_LEVEL_6_COST) && (getMembersCount() >= Config.GUILD_LEVEL_6_REQUIREMENT))
				{
					setReputationScore(getReputationScore() - Config.GUILD_LEVEL_6_COST, true);
					SystemMessage cr = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_GUILD_REP);
					cr.addNumber(Config.GUILD_LEVEL_6_COST);
					player.sendPacket(cr);
					cr = null;
					increaseGuildLevel = true;
				}
				break;
			
			case 6:
				// Upgrade to 7
				if ((getReputationScore() >= Config.GUILD_LEVEL_7_COST) && (getMembersCount() >= Config.GUILD_LEVEL_7_REQUIREMENT))
				{
					setReputationScore(getReputationScore() - Config.GUILD_LEVEL_7_COST, true);
					SystemMessage cr = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_GUILD_REP);
					cr.addNumber(Config.GUILD_LEVEL_7_COST);
					player.sendPacket(cr);
					cr = null;
					increaseGuildLevel = true;
				}
				break;
			case 7:
				// Upgrade to 8
				if ((getReputationScore() >= Config.GUILD_LEVEL_8_COST) && (getMembersCount() >= Config.GUILD_LEVEL_8_REQUIREMENT))
				{
					setReputationScore(getReputationScore() - Config.GUILD_LEVEL_8_COST, true);
					SystemMessage cr = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_GUILD_REP);
					cr.addNumber(Config.GUILD_LEVEL_8_COST);
					player.sendPacket(cr);
					cr = null;
					increaseGuildLevel = true;
				}
				break;
			case 8:
				// Upgrade to 9
				if ((getReputationScore() >= Config.GUILD_LEVEL_9_COST) && (player.getInventory().getItemByItemId(9910) != null) && (getMembersCount() >= Config.GUILD_LEVEL_9_REQUIREMENT))
				{
					// itemId 9910 == Blood Oath
					if (player.destroyItemByItemId("GuildLvl", 9910, 150, player.getTarget(), false))
					{
						setReputationScore(getReputationScore() - Config.GUILD_LEVEL_9_COST, true);
						SystemMessage cr = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_GUILD_REP);
						cr.addNumber(Config.GUILD_LEVEL_9_COST);
						player.sendPacket(cr);
						cr = null;
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED);
						sm.addItemName(9910);
						sm.addItemNumber(150);
						player.sendPacket(sm);
						increaseGuildLevel = true;
					}
				}
				break;
			case 9:
				// Upgrade to 10
				if ((getReputationScore() >= Config.GUILD_LEVEL_10_COST) && (player.getInventory().getItemByItemId(9911) != null) && (getMembersCount() >= Config.GUILD_LEVEL_10_REQUIREMENT))
				{
					// itemId 9911 == Blood Alliance
					if (player.destroyItemByItemId("GuildLvl", 9911, 5, player.getTarget(), false))
					{
						setReputationScore(getReputationScore() - Config.GUILD_LEVEL_10_COST, true);
						SystemMessage cr = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_GUILD_REP);
						cr.addNumber(Config.GUILD_LEVEL_10_COST);
						player.sendPacket(cr);
						cr = null;
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED);
						sm.addItemName(9911);
						sm.addItemNumber(5);
						player.sendPacket(sm);
						increaseGuildLevel = true;
					}
				}
				break;
			case 10:
				// Upgrade to 11
				boolean hasTerritory = false;
				for (Territory terr : TerritoryWarManager.getInstance().getAllTerritories())
				{
					if (terr.getOwnerGuild().getGuildId() == getGuildId())
					{
						hasTerritory = true;
						break;
					}
				}
				if (hasTerritory && (getReputationScore() >= Config.GUILD_LEVEL_11_COST) && (getMembersCount() >= Config.GUILD_LEVEL_11_REQUIREMENT))
				{
					setReputationScore(getReputationScore() - Config.GUILD_LEVEL_11_COST, true);
					SystemMessage cr = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_GUILD_REP);
					cr.addNumber(Config.GUILD_LEVEL_11_COST);
					player.sendPacket(cr);
					cr = null;
					increaseGuildLevel = true;
				}
				break;
			default:
				return false;
		}
		
		if (!increaseGuildLevel)
		{
			player.sendPacket(SystemMessageId.FAILED_TO_INCREASE_GUILD_LEVEL);
			return false;
		}
		
		// the player should know that he has less sp now :p
		StatusUpdate su = new StatusUpdate(player);
		su.addAttribute(StatusUpdate.SP, player.getSp());
		player.sendPacket(su);
		
		ItemList il = new ItemList(player, false);
		player.sendPacket(il);
		
		changeLevel(getLevel() + 1);
		return true;
	}
	
	public void changeLevel(int level)
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET guild_level = ? WHERE guild_id = ?"))
		{
			statement.setInt(1, level);
			statement.setInt(2, getGuildId());
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "could not increase guild level:" + e.getMessage(), e);
		}
		
		setLevel(level);
		
		if (getLeader().isOnline())
		{
			MMOPcInstance leader = getLeader().getPlayerInstance();
			if (4 < level)
			{
				SiegeManager.getInstance().addSiegeSkills(leader);
				leader.sendPacket(SystemMessageId.GUILD_CAN_ACCUMULATE_GUILD_REPUTATION_POINTS);
			}
			else if (5 > level)
			{
				SiegeManager.getInstance().removeSiegeSkills(leader);
			}
		}
		
		// notify all the members about it
		broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.GUILD_LEVEL_INCREASED));
		broadcastToOnlineMembers(new PledgeShowInfoUpdate(this));
		/*
		 * Micht : - use PledgeShowInfoUpdate instead of PledgeStatusChanged to update guild level ingame - remove broadcastGuildStatus() to avoid members duplication
		 */
		// guild.broadcastToOnlineMembers(new PledgeStatusChanged(guild));
		// guild.broadcastGuildStatus();
	}
	
	/**
	 * Change the guild crest. If crest id is 0, crest is removed. New crest id is saved to database.
	 * @param crestId if 0, crest is removed, else new crest id is set and saved to database
	 */
	public void changeGuildCrest(int crestId)
	{
		if (getCrestId() != 0)
		{
			CrestCache.getInstance().removePledgeCrest(getCrestId());
		}
		
		setCrestId(crestId);
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET crest_id = ? WHERE guild_id = ?"))
		{
			statement.setInt(1, crestId);
			statement.setInt(2, getGuildId());
			statement.executeUpdate();
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "Could not update crest for guild " + getName() + " [" + getGuildId() + "] : " + e.getMessage(), e);
		}
		
		for (MMOPcInstance member : getOnlineMembers(0))
		{
			member.broadcastUserInfo();
		}
	}
	
	/**
	 * Change the ally crest. If crest id is 0, crest is removed. New crest id is saved to database.
	 * @param crestId if 0, crest is removed, else new crest id is set and saved to database
	 * @param onlyThisGuild
	 */
	public void changeAllyCrest(int crestId, boolean onlyThisGuild)
	{
		String sqlStatement = "UPDATE guild_data SET ally_crest_id = ? WHERE guild_id = ?";
		int allyId = getGuildId();
		if (!onlyThisGuild)
		{
			if (getAllyCrestId() != 0)
			{
				CrestCache.getInstance().removeAllyCrest(getAllyCrestId());
			}
			sqlStatement = "UPDATE guild_data SET ally_crest_id = ? WHERE ally_id = ?";
			allyId = getAllyId();
		}
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(sqlStatement))
		{
			statement.setInt(1, crestId);
			statement.setInt(2, allyId);
			statement.executeUpdate();
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "Could not update ally crest for ally/guild id " + allyId + " : " + e.getMessage(), e);
		}
		
		if (onlyThisGuild)
		{
			setAllyCrestId(crestId);
			for (MMOPcInstance member : getOnlineMembers(0))
			{
				member.broadcastUserInfo();
			}
		}
		else
		{
			for (MMOGuild guild : GuildTable.getInstance().getGuildAllies(getAllyId()))
			{
				guild.setAllyCrestId(crestId);
				for (MMOPcInstance member : guild.getOnlineMembers(0))
				{
					member.broadcastUserInfo();
				}
			}
		}
	}
	
	/**
	 * Change the large crest. If crest id is 0, crest is removed. New crest id is saved to database.
	 * @param crestId if 0, crest is removed, else new crest id is set and saved to database
	 */
	public void changeLargeCrest(int crestId)
	{
		if (getCrestLargeId() != 0)
		{
			CrestCache.getInstance().removePledgeCrestLarge(getCrestLargeId());
		}
		
		setCrestLargeId(crestId);
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE guild_data SET crest_large_id = ? WHERE guild_id = ?"))
		{
			statement.setInt(1, crestId);
			statement.setInt(2, getGuildId());
			statement.executeUpdate();
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "Could not update large crest for guild " + getName() + " [" + getGuildId() + "] : " + e.getMessage(), e);
		}
		
		for (MMOPcInstance member : getOnlineMembers(0))
		{
			member.broadcastUserInfo();
		}
	}
	
	/**
	 * Check if this guild can learn the skill for the given skill ID, level.
	 * @param skillId
	 * @param skillLevel
	 * @return {@code true} if skill can be learned.
	 */
	public boolean isLearnableSubSkill(int skillId, int skillLevel)
	{
		MMOSkill current = _subPledgeSkills.get(skillId);
		// is next level?
		if ((current != null) && ((current.getLevel() + 1) == skillLevel))
		{
			return true;
		}
		// is first level?
		if ((current == null) && (skillLevel == 1))
		{
			return true;
		}
		// other sub-pledges
		for (SubPledge subunit : _subPledges.values())
		{
			// disable academy
			if (subunit.getId() == -1)
			{
				continue;
			}
			current = subunit.getSkill(skillId);
			// is next level?
			if ((current != null) && ((current.getLevel() + 1) == skillLevel))
			{
				return true;
			}
			// is first level?
			if ((current == null) && (skillLevel == 1))
			{
				return true;
			}
		}
		return false;
	}
	
	public boolean isLearnableSubPledgeSkill(MMOSkill skill, int subType)
	{
		// academy
		if (subType == -1)
		{
			return false;
		}
		
		int id = skill.getId();
		MMOSkill current;
		if (subType == 0)
		{
			current = _subPledgeSkills.get(id);
		}
		else
		{
			current = _subPledges.get(subType).getSkill(id);
		}
		// is next level?
		if ((current != null) && ((current.getLevel() + 1) == skill.getLevel()))
		{
			return true;
		}
		// is first level?
		if ((current == null) && (skill.getLevel() == 1))
		{
			return true;
		}
		
		return false;
	}
	
	public SubPledgeSkill[] getAllSubSkills()
	{
		FastList<SubPledgeSkill> list = FastList.newInstance();
		for (MMOSkill skill : _subPledgeSkills.values())
		{
			list.add(new SubPledgeSkill(0, skill.getId(), skill.getLevel()));
		}
		for (SubPledge subunit : _subPledges.values())
		{
			for (MMOSkill skill : subunit.getSkills())
			{
				list.add(new SubPledgeSkill(subunit.getId(), skill.getId(), skill.getLevel()));
			}
		}
		SubPledgeSkill[] result = list.toArray(new SubPledgeSkill[list.size()]);
		FastList.recycle(list);
		return result;
	}
	
	// Listeners
	/**
	 * Fires the guild creation listeners, if any.
	 */
	private void fireGuildCreationListeners()
	{
		if (!guildCreationListeners.isEmpty())
		{
			GuildCreationEvent event = new GuildCreationEvent();
			event.setGuild(this);
			for (GuildCreationListener listener : guildCreationListeners)
			{
				listener.onGuildCreate(event);
			}
		}
	}
	
	/**
	 * Fires all the GuildMemberShipListener.onLeaderChange() methods, if any. Prevents the guild leader change if it returns false;
	 * @param newLeader
	 * @param exLeader
	 * @return
	 */
	private boolean fireGuildLeaderChangeListeners(MMOPcInstance newLeader, MMOPcInstance exLeader)
	{
		if (!guildMembershipListeners.isEmpty() && (newLeader != null) && (exLeader != null))
		{
			GuildLeaderChangeEvent event = new GuildLeaderChangeEvent();
			event.setGuild(this);
			event.setNewLeader(newLeader);
			event.setOldLeader(exLeader);
			for (GuildMembershipListener listener : guildMembershipListeners)
			{
				if (!listener.onLeaderChange(event))
				{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * Fires all the GuildMembershipListener.onJoin() methods, if any<br>
	 * Returns true/false -> allow the player to join or not
	 * @param player
	 * @return
	 */
	private boolean fireGuildJoinListeners(MMOPcInstance player)
	{
		if (!guildMembershipListeners.isEmpty() && (player != null))
		{
			GuildJoinEvent event = new GuildJoinEvent();
			event.setGuild(this);
			event.setPlayer(player);
			for (GuildMembershipListener listener : guildMembershipListeners)
			{
				if (!listener.onJoin(event))
				{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * Fires all the GuildMembershipListener.onLeave() methods, if any<br>
	 * Returns true/false -> the player can leave the guild or not
	 * @param objectId - the guild member's objectId
	 * @return
	 */
	private boolean fireGuildLeaveListeners(int objectId)
	{
		if (!guildMembershipListeners.isEmpty())
		{
			GuildLeaveEvent event = new GuildLeaveEvent();
			event.setPlayerId(objectId);
			event.setGuild(this);
			for (GuildMembershipListener listener : guildMembershipListeners)
			{
				if (!listener.onLeave(event))
				{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * Fires all the GuildCreationListener.onGuildLevelUp() methods, if any<br>
	 * Blocks the level up if it returns false
	 * @return
	 */
	private boolean fireGuildLevelUpListeners()
	{
		if (!guildCreationListeners.isEmpty())
		{
			GuildLevelUpEvent event = new GuildLevelUpEvent();
			event.setGuild(this);
			event.setOldLevel(_level);
			for (GuildCreationListener listener : guildCreationListeners)
			{
				if (!listener.onGuildLevelUp(event))
				{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * Adds a guild creation listener
	 * @param listener
	 */
	public static void addGuildCreationListener(GuildCreationListener listener)
	{
		if (!guildCreationListeners.contains(listener))
		{
			guildCreationListeners.add(listener);
		}
	}
	
	/**
	 * Removes a guild creation listener
	 * @param listener
	 */
	public static void removeGuildCreationListener(GuildCreationListener listener)
	{
		guildCreationListeners.remove(listener);
	}
	
	/**
	 * Adds a guild join listener (a player just joined the guild)
	 * @param listener
	 */
	public static void addGuildMembershipListener(GuildMembershipListener listener)
	{
		if (!guildMembershipListeners.contains(listener))
		{
			guildMembershipListeners.add(listener);
		}
	}
	
	/**
	 * Removes a guild join listener (a player left the guild)
	 * @param listener
	 */
	public static void removeGuildMembershipListener(GuildMembershipListener listener)
	{
		guildMembershipListeners.remove(listener);
	}
}
